<?php
/*
 * Search for users.
 */

// authenticate user first
F3::call('authentication.php');
if (F3::exists('auth_error'))
{
  // authentication failed
  return;
}

// check that we have at least some search parameters
if (!F3::exists('GET.email') && !F3::exists('GET.nickname'))
{
  // we need at least either email or nickname
  header('HTTP/1.1 500');
  header("Content-Type: application/json");
  $err = array("error_message" => "No search parameters supplied.");
  echo json_encode($err);
  return;
}

// search for users
if (F3::exists('GET.email') && F3::exists('GET.nickname'))
{
  $sql = "SELECT id, nickname FROM user WHERE email LIKE '%?%' AND nickname LIKE '%?%' ORDER BY nickname";
  $param = array('1' => "%".F3::get('GET.email')."%", '2' => "%".F3::get('GET.nickname')."%");
}
else if (F3::exists('GET.email'))
{
  $sql = "SELECT id, nickname FROM user WHERE email LIKE ? ORDER BY nickname";
  $param = array('1' => "%".F3::get('GET.email')."%");
}
else if (F3::exists('GET.nickname'))
{
  $sql = "SELECT id, nickname FROM user WHERE nickname LIKE ? ORDER BY nickname";
  $param = array('1' => "%".F3::get('GET.nickname')."%");
}

$result = DB::sql($sql, $param);
$response = array();
foreach ($result as $row) {
	$r = array();
	$r['id'] = $row['id'];
	$r['nickname'] = $row['nickname'];
	array_push($response, $r);
}

header('HTTP/1.1 200');
header("Content-Type: application/json");
echo json_encode($response);

?>
